package com.example.leero.graduation.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.leero.graduation.API;
import com.example.leero.graduation.App;
import com.example.leero.graduation.BaseActivity;
import com.example.leero.graduation.R;
import com.example.leero.graduation.Util.DateUtil;
import com.example.leero.graduation.Util.FileUtil;
import com.example.leero.graduation.Util.ImageLoader;
import com.example.leero.graduation.Util.ImageUtil;
import com.example.leero.graduation.Util.LogUtil;
import com.example.leero.graduation.Util.StringUtil;
import com.example.leero.graduation.Util.permisssion.PermissionReq;
import com.example.leero.graduation.Util.permisssion.PermissionResultImpl;
import com.example.leero.graduation.Util.permisssion.Permissions;
import com.example.leero.graduation.customView.ClearEditText;
import com.example.leero.graduation.customView.LoadingDialog;
import com.example.leero.graduation.model.User;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;

/**
 * Created by Leero on 2017-4-25.
 */

public class EditActivity extends BaseActivity {

    private ImageButton back;
    private RelativeLayout rl_avatar;
    private ImageView iv_user_icon;
    private ClearEditText et_nickname, et_signature, et_college;
    private TextView tv_birthday;
    private RadioGroup rg_sex;
    private RadioButton rb_man, rb_women;
    private Button btn_commit;
    private Spinner sp_emotion;

    private int mYear, mMonth, mDay;
    private final int DATE_DIALOG = 1;
    private static final int REQUEST_IMAGE = 0;
    private static final String[] emotions = {"单身", "恋爱中", "保密", "同性"};
    private int emotionSelect = 0;
    private int sexSelected = 1;   // 默认男为1

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_info;
    }

    @Override
    protected void initView(Bundle state) {
        addView();
        initData();

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rl_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionReq.with(EditActivity.this)
                        .permissions(getPermissions())
                        .result(new PermissionResultImpl(EditActivity.this) {
                            @Override
                            public void onGranted() {
                                openImageSelector();
                            }
                        })
                        .request();
            }
        });

        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rBtn = (RadioButton) findViewById(group.getCheckedRadioButtonId());
                if (StringUtil.equals("男", rBtn.getText().toString())) {
                    sexSelected = 1;
                } else {
                    sexSelected = 0;
                }
            }
        });

        tv_birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(DATE_DIALOG);
            }
        });

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postUserData();
            }
        });
    }

    private void addView() {
        back = (ImageButton) findViewById(R.id.iv_left);
        rl_avatar = (RelativeLayout) findViewById(R.id.rl_avatar);
        iv_user_icon = (ImageView) findViewById(R.id.iv_user_icon);
        et_nickname = (ClearEditText) findViewById(R.id.et_nickname);
        et_signature = (ClearEditText) findViewById(R.id.et_signature);
        et_college = (ClearEditText) findViewById(R.id.et_college);
        tv_birthday = (TextView) findViewById(R.id.tv_birthday);
        rg_sex = (RadioGroup) findViewById(R.id.rg_sex);
        btn_commit = (Button) findViewById(R.id.btn_commit);
        sp_emotion = (Spinner) findViewById(R.id.sp_emotion);
        rb_man = (RadioButton) findViewById(R.id.rb_man);
        rb_women = (RadioButton) findViewById(R.id.rb_women);
        setupSpinner();

        final Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);

        iv_user_icon = (ImageView) findViewById(R.id.iv_user_icon);
    }

    private void initData() {
        User user = App.getLoginUser();
        if (!StringUtil.isEmpty(user.user_icon)) {
            ImageLoader.load(EditActivity.this, iv_user_icon, user.user_icon);
        } else {
            iv_user_icon.setImageResource(R.drawable.default_avatar_cricle);
        }

        et_nickname.setText(user.nickname);
        tv_birthday.setText(user.birthday);

        if(user.sex == 1) {
            rb_man.setChecked(true);
            rb_women.setChecked(false);
            sexSelected = 1;
        } else {
            rb_man.setChecked(false);
            rb_women.setChecked(true);
            sexSelected = 0;
        }
        sp_emotion.setSelection(user.affective_state, true);
        et_signature.setText(user.per_signature);
        et_college.setText(user.college);
    }

    private void setupSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, emotions);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_emotion.setAdapter(adapter);

        sp_emotion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                emotionSelect = position;
                LogUtil.setShow(true);
                LogUtil.w("选择的情感状态是" + emotionSelect);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_IMAGE) {
                LoadingDialog.show(this);
                List<String> paths = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                String targetDir = FileUtil.getAppCache(this, "temp");
                String path = ImageUtil.compressImage(paths.get(0), targetDir, 30);
                changeAvatar(path);
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    /**
     * 设置日期 利用StringBuffer追加
     */
    public void display() {
        tv_birthday.setText(new StringBuffer().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay).append(" "));
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display();
        }
    };

    /**
     * 换头像需要的权限：相机、读写内存
     * @return
     */
    private String[] getPermissions() {
        String[] p = new String[3];
        p[0] = Permissions.CAMERA[0];
        p[1] = Permissions.STORAGE[0];
        p[2] = Permissions.STORAGE[1];
        return p;
    }

    public void openImageSelector() {
        MultiImageSelector.create()
                .single()
                .showCamera(true)
                .start(this, REQUEST_IMAGE);
    }

    public void changeAvatar(String path) {
        File f = new File(path);
        OkHttpUtils.post().url(API.UPLOAD_AVATAR)
                .addParams("user_id", App.getLoginUser().id+"")
                .addFile("avatar", f.getName(), f)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (!StringUtil.isEmpty(jsonObject.getString("avatar"))) {
                        ImageLoader.load(EditActivity.this, iv_user_icon, jsonObject.getString("avatar"));
                        Toast.makeText(EditActivity.this, "头像更新了", Toast.LENGTH_SHORT).show();
                    } else {
                        iv_user_icon.setImageResource(R.drawable.default_avatar_cricle);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onAfter(int id) {
                LoadingDialog.dismissDialog();
            }
        });

    }



    private void postUserData() {
        OkHttpUtils.post().url(API.EDIT_ACCOUNT)
                .addParams("user_id", App.getLoginUser().id + "")
                .addParams("nickname", et_nickname.getText().toString())
                .addParams("birthday", tv_birthday.getText().toString())
                .addParams("sex", "" + sexSelected)
                .addParams("affective_state", "" + emotionSelect)
                .addParams("per_signature", et_signature.getText().toString())
                .addParams("college", et_college.getText().toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getBoolean("state")) {
                        EditActivity.this.finish();
                    } else {
                        Toast.makeText(EditActivity.this, "服务器开小差了", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

}
